import React, { Component } from 'react'
import Input from './components/Input'
import { createForm } from './components/my-rc-form'

const nameRules = [{
    require: true, message: '请输入姓名'
}, {
    minLength: 3, message: '用户名不能少于3个字'
}]
const passwordRules = [{ require: true, message: '请输入密码' }]

@createForm //加上装饰器后，props里面就生成一个form对象，具备Form提供的各种方法和属性了
class Index2 extends Component {
    constructor(props) {
        super(props)
        this.state = { errInfo: [] }
    }
    componentDidMount() {
        const { setFieldsValue } = this.props.form
        setFieldsValue({username:'d',password:''})
    }
    submit() {
        const { getFieldsValue, getFieldValue, validateFields } = this.props.form
        console.log('~~rc-form提交信息', getFieldsValue(), getFieldValue('username'), getFieldValue('password'))
        console.log('~~this.props', this.props)
        validateFields((err, data) => {
            if (err) {
                console.log('~~校验失败', err)
                this.setState({ errInfo: err })
            } else {
                console.log('~~校验成功', data)
                this.setState({ errInfo: [] })
                alert('~~校验成功')
            }
        })

    }
    render() {
        const { getFieldDecorator } = this.props.form
        return (
            <div>
                {this.state.errInfo.length > 0
                    ? <p style={{ color: 'red' }}>~~校验失败: {this.state.errInfo.map(item => <li>{JSON.stringify(item)}</li>)}</p>
                    : null
                }
                {getFieldDecorator('username', { rules: nameRules })(
                    <Input placeholder='请输入用户名' />
                )}
                {getFieldDecorator('password', { rules: passwordRules })(
                    <Input placeholder='请输入密码' type='password' />
                )}
                <button onClick={() => this.submit()}>submit</button>
            </div>
        );
    }
}

export default Index2;
